import numpy as np
from scipy import signal
import json
import os

def design_bandpass_filters(fs=250, low_freq=0.5, high_freq=30, order=4):
    """
    设计带通滤波器参数
    
    参数:
    fs: 采样率 (Hz)
    low_freq: 最低频率 (Hz)
    high_freq: 最高频率 (Hz)
    order: 滤波器阶数
    
    返回:
    包含滤波器参数的字典
    """
    print("design_bandpass_filters:")
    print(f"fs: {fs}, low_freq: {low_freq}, high_freq: {high_freq}, order: {order}")

    filter_params = {}
    
    # 归一化频率
    nyq = fs * 0.5
    low = low_freq / nyq
    high = high_freq / nyq
    
    # 设计Butterworth滤波器
    b, a = signal.butter(order, [low, high], btype='bandpass')
    
    # 将 b 和 a 数组中的每个元素限制为10位小数
    b = np.floor(b * 1e10) / 1e10
    a = np.floor(a * 1e10) / 1e10
    
    # 存储参数
    key = f"{low_freq:.1f}-{high_freq:.1f}"
    filter_params[key] = {
        'b': b.tolist(),
        'a': a.tolist(),
        'f1': float(low_freq),
        'f2': float(high_freq),
        'fs': fs,
        'order': order
    }
    
    return filter_params

def save_filter_params(params, filename):
    """保存滤波器参数到JSON文件"""
    with open(filename, 'w') as f:
        json.dump(params, f, indent=4)
    print(f"参数已保存到 {filename}")

def filter_params(args):

    parse_args = json.loads(args)
    fs = parse_args["sample_rate"]
    low = parse_args["lowpass"]
    high = parse_args["highpass"]
    order = parse_args["order"]

    # 设计滤波器参数
    params = design_bandpass_filters(
        fs,          # 采样率
        low,    # 最低频率
        high,    # 最高频率
        order          # 滤波器阶数
    )

    # 保存参数
    current_file_path = os.path.abspath(__file__)
    current_dir = os.path.dirname(current_file_path)
    bandpass_filter_params_file_path = current_dir + "/bandpass_filter_params.json"
    save_filter_params(params, bandpass_filter_params_file_path)
    
    # 打印滤波器参数
    key = list(params.keys())[0]
    print("\n滤波器参数:")
    print(f"频率范围: {key} Hz")
    print(f"分子系数 (b): {params[key]['b']}")
    print(f"分母系数 (a): {params[key]['a']}")

    response = {
        "a": params[key]['a'],
        "b": params[key]['b'],
    }
    return json.dumps(response)

def main():
    # 设计滤波器参数
    params = design_bandpass_filters(
        fs=250,          # 采样率
        low_freq=10,    # 最低频率
        high_freq=20,    # 最高频率
        order=4          # 滤波器阶数
    )
    
    # 保存参数
    save_filter_params(params, "bandpass_filter_params.json")
    
    # 打印滤波器参数
    key = list(params.keys())[0]
    print("\n滤波器参数:")
    print(f"频率范围: {key} Hz")
    print(f"分子系数 (b): {params[key]['b']}")
    print(f"分母系数 (a): {params[key]['a']}")

    response = {
        "a": params[key]['a'],
        "b": params[key]['b'],
    }
    print(json.dumps(response))

# 测试代码，框架运行时需要注释掉
if __name__ == "__main__":
    main()
